package coder.nav.service;

import coder.nav.enums.NavSettingEnums;
import coder.nav.model.NavSetting;
import coder.nav.model.bo.NavFanyiBO;
import coder.nav.model.vo.NavFanyiVO;
import coder.nav.model.vo.NavListVO;
import coder.nav.sdk.BaiduTransAPI;
import coder.nav.utils.ChineseUtils;
import coder.nav.utils.JwtUtils;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class NavListService {

    @Lazy
    @Autowired
    private NavSettingService settingService;

    /**
     * 默认列表（没有设置的获取 userId = 1 的数据）
     */
    public List<NavListVO> getList() {
        Long userId = 1L;
        try {
            userId = JwtUtils.getUserId(); // 未登录的使用 userId = 1 的数据
        } catch(Exception ignored) {}
        LambdaQueryWrapper<NavSetting> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(NavSetting::getType, NavSettingEnums.NAV.getKey())
                .eq(NavSetting::getUserId, userId);
        NavSetting setting = settingService.getOne(queryWrapper);
        if(Objects.isNull(setting)) {
            // 已登录但数据为空的使用 userId = 1 的数据
            LambdaQueryWrapper<NavSetting> defaultQueryWrapper = new LambdaQueryWrapper<>();
            defaultQueryWrapper.eq(NavSetting::getType, NavSettingEnums.NAV.getKey())
                    .eq(NavSetting::getUserId, 1L);
            setting = settingService.getOne(defaultQueryWrapper);
            if(Objects.isNull(setting)) {
                return null;
            }
        }
        return JSONArray.parseArray(setting.getParams(), NavListVO.class);
    }

    /**
     * 翻译接口
     * @param bo 入参
     */
    public NavFanyiVO getFanyiResult(NavFanyiBO bo) {
        NavFanyiVO vo = new NavFanyiVO(bo.getKeyword());
        String from = "auto";
        String to = "zh";
        if(ChineseUtils.isAllChinese(bo.getKeyword())) {
            to = "en";
        }
        String result = BaiduTransAPI.getResult(bo.getKeyword(), from, to);
        if(StringUtils.isNotBlank(result)) {
            vo.setValue(result);
        }
        return vo;
    }

}
